import {Component, OnInit} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {OutStoreSelectDeviceComponent} from '../../used-store/out-store/out-store-add/out-store-select-device/out-store-select-device.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {UserLabelAddComponent} from '../../../sharedModule/commponent/user-label-add/user-label-add.component';
import {CommonService} from '../../../services-common/common.service';
import {NzMessageService} from 'ng-zorro-antd/message';

@Component({
  selector: 'app-customer-label',
  templateUrl: './customer-label.component.html',
  styleUrls: ['./customer-label.component.scss']
})
export class CustomerLabelComponent implements OnInit {

  // 查询条件
  query = {
    contentList: '',
    tagList: [],
    userId: '',
    userType: [],
    date: [],
    // 当前页
    page: 1,
    // 分页大小
    pageSize: 20,
  };
  // 表格数据
  listOfData = {
    page: 1,
    total: 100,
    records: []
  };
  category = [];
  tageContent = [];
  destroyLabelModal = {
    visible: false,
    id: '',
    userId: '',
    remark: '',
  };

  constructor(
    private httpClient: HttpClient,
    private nzModalService: NzModalService,
    private commonService: CommonService,
    private nzMessageService: NzMessageService,
  ) {
  }

  ngOnInit(): void {
    this.getTableData();
    this.getDictData();
  }

  onPageIndexChange(index: number) {
    this.query.page = index;
    this.getTableData();
  }

  onPageSizeChange(pageSize: number) {
    this.query.pageSize = pageSize;
    this.getTableData();
  }

  queryBtn() {
    this.query.page = 1;
    this.getTableData();
  }

  resetCondition() {
    this.query = {
      tagList: [],
      contentList: '',
      userType: [],
      userId: '',
      date: [],
      page: 1,
      pageSize: 20,
    };
    this.queryBtn();
  }

  getTableData() {
    // contentList  标签内容分类
    // tagList  标签分类
    // userId  用户id
    // beginOperateTime  操作开始时间
    // endOperateTime  操作结束时间
    this.httpClient.post('/userTag/list', {
      contentList: this.query.contentList ? this.query.contentList.split(',') : [],
      tagList: this.query.tagList.join(','),
      userType: this.query.userType.join(','),
      userId: this.query.userId,
      beginOperateTime: this.formatTime(this.query.date ? this.query.date[0] : '', 'date'),
      endOperateTime: this.formatTime(this.query.date ? this.query.date[1] : '', 'date'),
      page: this.query.page,
      pageSize: this.query.pageSize,
    }).subscribe((res: any) => {
      if (res.code === 0) {
        this.listOfData = res.data;
      }
      console.log(res);
    });
  }

  getDictData() {
    this.dictData('user_tags_classify').then((res: any) => {
      if (res.code === 0) {
        this.category = res.data.list.records;
      }
    });
    this.dictData('user_tags_preset').then((res: any) => {
      if (res.code === 0) {
        this.tageContent = res.data.list.records;
      }
    });
  }


  formatTime(date: any, type: 'date' | 'dateTime' | 'time') {
    if (!date || (typeof date) === 'string') {
      return date || '';
    }
    let result = '';
    switch (type) {
      case 'date':
        // @ts-ignore
        result = date.toISOString().match(/\d{4}-\d{2}-\d{2}/)[0];
        break;
      case 'dateTime':
        // @ts-ignore
        result = date.toISOString().match(/\d{4}-\d{2}-\d{2}/)[0] + ' ' + date.toString().match(/\d{2}:\d{2}:\d{2}/)[0];
        break;
      case 'time':
        // @ts-ignore
        result = date.toString().match(/\d{2}:\d{2}:\d{2}/)[0];
        break;
    }
    return result;
  }

  showDestroyLabelModal(data: any) {
    this.destroyLabelModal.visible = true;
    this.destroyLabelModal.id = data.id;
    this.destroyLabelModal.userId = data.userId;
  }

  hideDestroyLabelModal() {
    this.destroyLabelModal = {
      visible: false,
      id: '',
      userId: '',
      remark: '',
    };
  }

  destroyLabel() {
    this.httpClient.post('/userTag/cancel', {
      id: this.destroyLabelModal.id,
      userId: this.destroyLabelModal.userId,
      remark: this.destroyLabelModal.remark
    }).subscribe((res: any) => {
      if (res.code === 0) {
        this.hideDestroyLabelModal();
        this.getTableData();
      }
    });
  }

  // 查询渠道（字典）
  dictData(parentKey: any) {
    const params: any = {
      pageNum: 1,
      pageSize: 9999,
      parentKey
    };
    return this.httpClient.get('/dict/detail', {params}).toPromise();
  }

  addLabel(userId: any) {
    const modal = this.nzModalService.create({
      nzTitle: '用户打标',
      nzContent: UserLabelAddComponent,
      nzFooter: null,
      nzWidth: '400px',
      nzMaskClosable: false,
      nzComponentParams: {
        userId
      },
    });
    modal.afterClose.subscribe(res => {
      if (res && res.refresh) {
        this.getDictData();
        this.getTableData();
      }
    });
  }


  export() {
    this.nzModalService.confirm({
      nzTitle: '提示',
      nzContent: '即将导出符合本页面筛选条件的订单数据，为了导出速度请尽可能控制时间范围。确定导出？',
      nzOkText: '确定',
      nzOkType: 'primary',
      nzOkDanger: true,
      nzOnOk: async () => {
        const body = {
          contentList: this.query.contentList ? this.query.contentList.split(',') : [],
          tagList: this.query.tagList.join(','),
          userType: this.query.userType.join(','),
          userId: this.query.userId,
          beginOperateTime: this.formatTime(this.query.date ? this.query.date[0] : '', 'date'),
          endOperateTime: this.formatTime(this.query.date ? this.query.date[1] : '', 'date'),
        };
        const res: any = await this.httpClient.post('/userTag/findExcel', body, {responseType: 'blob'}).toPromise();
        if (res.type === 'application/octet-stream') {
          this.commonService.downLoadBlobFile(res, '用户标签');
        } else {
          this.nzMessageService.error('导出失败');
        }
      },
      nzCancelText: '关闭'
    });
  }
}
